import React from "react";  
import classes from './QuizList.css';  
import Loader from "../../components/UI/Loader/Loader";  
import { NavLink } from "react-router-dom";  
import axios from "../../axios/axios-quiz";  
import { connect } from 'react-redux';  
import { fetchQuizesStart, fetchQuizesSuccess, fetchQuizesFail } from '../../store/reducers/quizReducer';
  
class QuizList extends React.Component {  
    async componentDidMount() {  
        this.props.fetchQuizesStart();  
        try {  
            const response = await axios.get('/quizes.json');  
  
            const quizes = [];  
            Object.keys(response.data).forEach((key, index) => {  
                quizes.push({  
                    id: key,  
                    name: `Тест №${index + 1}`  
                });  
            });  
  
            this.props.fetchQuizesSuccess(quizes);  
        } catch (e) {  
            this.props.fetchQuizesFail();  
            console.log("Error: ", e);  
        }  
    }  
  
    renderQuizes() {  
        return this.props.quizes.map((quiz) => {  
            return (  
                <li key={quiz.id}>  
                    <NavLink to={'/quiz/' + quiz.id}>  
                        {quiz.name}  
                    </NavLink>  
                </li>  
            );  
        });  
    }  
  
    render() {  
        return (  
            <div className={classes.QuizList}>  
                <div>  
                    <h1>Список тестов</h1>  
                    {  
                        this.props.loading  
                            ? <Loader />  
                            : <ul>  
                                {this.renderQuizes()}  
                              </ul>  
                    }  
                </div>  
            </div>  
        );  
    }  
}  
  
const mapStateToProps = state => {  
    return {  
        quizes: state.quiz.quizes, 
        loading: state.quiz.loading  
    };  
};  
  
const mapDispatchToProps = {  
    fetchQuizesStart,  
    fetchQuizesSuccess,  
    fetchQuizesFail  
};
  
export default connect(mapStateToProps, mapDispatchToProps)(QuizList);  
